// 封装cookie

// 1.写入Cookie
const set = (name, value, { domain, path, maxAge, secure } = {}) => {
    // 添加编码encodeURIComponent
    let cookieText = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`

    if (typeof maxAge === 'number') {
        cookieText += `; max-age=${maxAge}`
    }

    if (domain) {
        cookieText += `; domain=${domain}`
    }
    if (path) {
        cookieText += `; path=${path}`
    }
    if (secure) {
        cookieText += `; secure=${secure}`
    }
    document.cookie = cookieText
}

// 2.通过name获取cookie
const get = (name) => {
    // 编码
    name = `${encodeURIComponent(name)}`
    const cookies = document.cookie.split('; ')
    for (let item of cookies) {
        const [cookieName, cookieValue] = item.split('=')
        if (cookieName === name) {
            return decodeURIComponent(cookieValue)//解码返回，不然汉字返回的是乱码
        }
    }

    return
}

// 3.根据name，domain，path删除cookie
const remove = (name, { domain, path } = {}) => {
    name = `${encodeURIComponent(name)}`
    set(name, '', { domain, path, maxAge: -1 })
}
export { set, get, remove }